package www.dianbaozu.com.ui.server

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context.CLIPBOARD_SERVICE
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.view.isGone
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.lxj.xpopup.core.BasePopupView
import com.netease.nim.uikit.api.NIMHelper
import com.netease.nim.uikit.xpopup.CreateXPopupHelper
import com.netease.nim.uikit.xpopup.PopupViewEntity
import com.netease.nim.uikit.xpopup.popuview.BottomSharePosterPopupView
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import www.dianbaozu.com.R
import www.dianbaozu.com.databinding.FragmentServerDetailsBinding
import www.dianbaozu.com.extension.requestUniversally
import www.wen.com.common.lib.app.BaseApplication
import www.wen.com.common.lib.base.fragment.BaseLoadingFragment
import www.wen.com.common.lib.base.module.BaseApiViewModel
import www.wen.com.common.lib.data.entities.*
import www.wen.com.common.lib.extension.*
import www.wen.com.common.lib.extension.glide.setImageUrl
import www.wen.com.common.lib.helper.loading.KeyHelper
import www.wen.com.common.lib.helper.loading.KeyHelper.BUNDLE_DATA
import www.wen.com.common.lib.helper.loading.KeyHelper.REFRESH_SERVER_MESSAGE_TYPE_KEY
import www.wen.com.common.lib.helper.loading.PathHelper
import www.wen.com.common.lib.helper.loading.TitleBarUniversalAdapter
import www.wen.com.common.lib.util.BitmapUtil
import www.wen.com.common.lib.util.FileUtils
import www.wen.com.common.lib.util.SpUtil
import www.wen.com.common.lib.util.WxUtil
import www.wen.com.common.lib.util.WxUtil.shareText
import java.io.File
import kotlin.concurrent.thread


/**
 * @author WEN
 * @Description:服务器管理详情,分管理员与非管理员的情况
 * @date 2020//25 17:48
 */
@AndroidEntryPoint
class ServerDetailsFragment : BaseLoadingFragment<FragmentServerDetailsBinding>(),
        View.OnClickListener {

    private lateinit var imgFile: File

    private val mIwxapi by lazy { WxUtil.getIWXAPI(requireActivity()) }

    private val mBaseApiViewModel: ServerDetailsViewModel by viewModels()

    private lateinit var mServerInfo: ServerInfo

    override val viewModel: BaseApiViewModel
        get() = mBaseApiViewModel

    override fun isEnableLoadingHelper() = true

    override fun getTitleBarUniversalAdapter(): TitleBarUniversalAdapter = TitleBarUniversalAdapter(
            requireActivity(),
            background = ContextCompat.getColor(BaseApplication.CONTEXT, R.color.color1B1D22),
            action = ::titleAction
    )

    override fun getLayoutId(): Int = R.layout.fragment_server_details

    override fun lazyInitView() {
        mServerInfo = requireArguments().getParcelable(BUNDLE_DATA)!!
        initializeUI()
        observeListen()
    }

    private fun initializeUI() {
        dataBinding.run {
            clBottomContainer.isGone = mServerInfo.serverMember!!.ownerFlag != "1"
            tvExitServer.isGone = mServerInfo.serverMember!!.ownerFlag == "1"
            setImageUrl(ivAvatar, mServerInfo.serverLogo.imgUrl())
            setImageUrl(
                    ivServerBg,
                    mServerInfo.serverBackground.imgUrl(),
                    R.drawable.bg_default_background_map
            )
            tvGroupName.text = mServerInfo.serverName
            switchAllow.isChecked = mServerInfo.serverMember!!.allowFriendFlag == "1"
            slAddServerBgImg.isInvisible =
                    mServerInfo.serverMember!!.ownerFlag != "1" || mServerInfo.serverBackground.isNotBlank()
            if (mServerInfo.serverMember!!.ownerFlag == "1" && mServerInfo.serverBackground.isNotBlank()) {
                clServerBg.setOnClickListener(this@ServerDetailsFragment)
            }
            "${mServerInfo.onlineCount}人在线".also { tvOnlineCount.text = it }
            "${mServerInfo.memberCount}位成员".also { tvMember.text = it }
        }
    }

    private fun observeListen() {

        //更新消息类型
        observeObject(REFRESH_SERVER_MESSAGE_TYPE_KEY, this, String::class.java) {
            mServerInfo.serverMember!!.noticeType = this
        }

        //更新头像、服务器名字
        observeObject(
                KeyHelper.UPDATE_SERVER_INFORMATION_KEY,
                this,
                ServerUpdateInfoEntity::class.java
        ) {
            dataBinding.run {
                serverName?.also {
                    tvGroupName.text = it
                    mServerInfo.serverName = it
                }
                serverLogo?.also {
                    setImageUrl(ivAvatar, it.imgUrl())
                    mServerInfo.serverLogo = it
                }
                serverIntro?.also { mServerInfo.serverIntro = it }
                nickNameInServer?.also { mServerInfo.serverMember!!.nickName = it }
            }
        }
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.clInviteFriends -> inviteFriends()
            R.id.slAvatar -> bigAvatar()
            R.id.tvNotificationSettings -> notificationSettings()
            R.id.tvModifyServerNickname -> modifyServerNickname()
            R.id.tvCreateNewGroup -> createNewGroup()
            R.id.tvCreateNewChannel -> createNewChannel()
            R.id.tvServerSettings -> serverSettings()
            R.id.tvInvite -> invite()
            R.id.AllowAddFriend -> allowAddFriend()
            R.id.tvMembers -> members()
            R.id.clServerBg,
            R.id.slAddServerBgImg,
            -> addServerBgImg()
            R.id.tvExitServer -> exitServer()
            R.id.flBigAvatar -> dataBinding.flBigAvatar.isVisible  = false
        }
    }

    private fun bigAvatar() {
        dataBinding.run {
            setImageUrl(ivBigAvatar,mServerInfo.serverLogo.imgUrl())
            flBigAvatar.isVisible  = true
        }
    }

    private fun exitServer() {
        CreateXPopupHelper.createShowStandardAlertPopupView(PopupViewEntity().apply {
            context = requireActivity()
            standardAlertPopupViewTitle = getString(R.string.com_delete_server)
            isShow = true
            standardAlertPopupViewCancelContent = "取消"
            standardAlertPopupViewConfirmContent = "确认"
            standardAlertPopupViewContent = "你确定要退出【${mServerInfo.serverName}】吗？\n\n该操作无法撤销"
            confirmFunction = { basePopupView ->
                basePopupView.dismiss()
                mBaseApiViewModel.requestUniversally(
                        viewModelScope = lifecycleScope,
                        tipLoading = getString(R.string.com_exiting_server),
                        isShowToastTip = false,
                        request = { appDataManage ->
                            appDataManage.requestExitServers(mServerInfo.serverId)
                        }
                ) {
                    mServerInfo.teamIds?.forEach {
                        NIMHelper.updateTeamUnreadCount(it, 0)
                    }
                    NIMHelper.updateAddFriendUnreadCount()
                    toast("退出【${mServerInfo.serverName}】成功")
                    //移除推荐被删除的服务器
                    postObject(KeyHelper.REMOVE_SERVER, mServerInfo.serverId)
                    //刷新首页服务列表,避免点击到已经退出的服务器
                    postObject(KeyHelper.REFRESHING_SERVER_LIST, Object())
                    //返回Main主页
                    popProxy(R.id.mainFragment)
                }
            }
        })
    }

    private fun addServerBgImg() {
        openPhotoAlbumAgency(
                aspect_ratio_x = 1125,
                aspect_ratio_y = 611,
        ) {
            val imgLocalFile =
                    if (it[0].androidQToPath.isNullOrBlank()) File(it[0].compressPath) else File(it[0].androidQToPath)
            if (imgLocalFile.exists()) {
                imgFile = imgLocalFile
                thread {
                    requireActivity().runOnUiThread {
                        mBaseApiViewModel.requestUpdateServerInfo(
                                partMap = mapOf(
                                        "userId" to SpUtil.decodeString(KeyHelper.MMKV_ID)!!
                                                .toRequestBody("text/plain".toMediaTypeOrNull())
                                ),
                                serverId = mServerInfo.serverId,
                                MultipartBody.Part.createFormData(
                                        "files",
                                        imgFile.name,
                                        imgFile.asRequestBody("image/jpeg".toMediaTypeOrNull())
                                )
                        ) { serverUpte ->
                            mServerInfo.serverBackground = serverUpte.serverBackground!!
                            setImageUrl(
                                    dataBinding.ivServerBg,
                                    imgFile.absolutePath,
                                    placeholder = R.drawable.bg_default_background_map
                            )
                            dataBinding.clServerBg.setOnClickListener(this@ServerDetailsFragment)
                            dataBinding.slAddServerBgImg.isInvisible = true

                            postObject(KeyHelper.UPDATE_SERVER_INFORMATION_KEY, ServerUpdateInfoEntity(serverId = mServerInfo.serverId,serverBackground = mServerInfo.serverBackground))
                        }
                    }
                }
            }
        }
    }

    private fun members() {
        nav(R.id.action_serverDetailsFragment_to_findMemberUseApiFragment, Bundle().apply {
            putParcelable(
                    BUNDLE_DATA,
                    RequestBodyParameter(
                            serverId = mServerInfo.serverId,
                            serverName = mServerInfo.serverName
                    )
            )
        })
    }

    private fun allowAddFriend() {
        val allowSwitch = if (mServerInfo.serverMember!!.allowFriendFlag == "1") "0" else "1"
        mBaseApiViewModel.requestUniversally(
                viewModelScope = lifecycleScope,
                isShowToastTip = false,
                request = { appDataManage ->
                    appDataManage.requestMemberSetting(
                            id = mServerInfo.serverMember!!.id.toString(),
                            RequestBodyParameter(
                                    allowFriendFlag = allowSwitch,
                                    serverId = mServerInfo.serverId
                            )
                    )
                }
        ) {
            mServerInfo.serverMember!!.allowFriendFlag =
                    if (mServerInfo.serverMember!!.allowFriendFlag == "1") "0" else "1"
            dataBinding.switchAllow.isChecked = !dataBinding.switchAllow.isChecked
        }
    }

    private fun inviteFriends() {
        mBaseApiViewModel.requestUniversally(
                viewModelScope = lifecycleScope,
                isShowToastTip = false,
                request = { appDataManage ->
                    appDataManage.requestServerShareUrl(
                            RequestBodyParameter(serverId = mServerInfo.serverId)
                    )
                }
        ) { shareUrlEntity ->
            CreateXPopupHelper.createBottomSharePopupView(PopupViewEntity().apply {
                isShow = true
                context = requireActivity()
                address = shareUrlEntity.shareUrl
                resultCallBack = { view, address, popupView ->
                    when (view.id) {
                        R.id.tvAddress -> {
                            val clipboard =
                                    requireActivity().getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
                            val clip = ClipData.newPlainText("simple text", address)
                            clipboard.setPrimaryClip(clip)
                            toast("复制成功")
                        }
                        R.id.llShareWeChat -> {
                            mIwxapi.shareText(address, false) {
                                popupView.dismiss()
                            }
                        }
                        R.id.llShareToFriends -> {
                            showSharePosterPopupView(popupView, address)
                        }
                    }
                }
            })
        }
    }

    private fun showSharePosterPopupView(urlPopupView: BasePopupView, address: String) {
        mBaseApiViewModel.requestUniversally(
                viewModelScope = lifecycleScope,
                isShowToastTip = false,
                request = { appDataManage ->
                    appDataManage.requestProtocol(mapOf("type" to "邀请海报"))
                }
        ) {
            urlPopupView.dismiss()
            CreateXPopupHelper.createBottomSharePosterPopupView(PopupViewEntity().apply {
                isShow = true
                context = requireActivity()
                protocolContent = it.content[0].apply { shareUrl = address }
                resultProtocolEntityCallBack =
                        { _: View, _: ProtocolEntity.Content, basePopupView: BasePopupView ->
                            try {
                                BitmapUtil.savePhotoAlbum(
                                        src = BitmapUtil.generateBitmapFromView(view = (basePopupView as BottomSharePosterPopupView).clPoster),
                                        file = FileUtils.getDeviceExternalFilesDir(
                                                PathHelper.POSTER_PATH,
                                                "${System.currentTimeMillis()}.jpg"
                                        ),
                                ) { _: String, _: Uri ->
                                    requireActivity().runOnUiThread {
                                        basePopupView.dismiss()
                                        toast("海报已保存到相册")
                                    }
                                }
                            } catch (e: Exception) {
                                toast("海报保存失败 ${e.message}")
                            }
                        }
            })
        }
    }

    private fun notificationSettings() {
        nav(R.id.action_serverDetailsFragment_to_notificationSettingsFragment, Bundle().apply {
            putParcelable(
                    BUNDLE_DATA,
                    BundleNotificationEntity(
                            mServerInfo.serverMember!!.noticeType,
                            mServerInfo.serverMember!!.id.toString(),
                            mServerInfo.serverId,
                            mServerInfo.teamIds
                    )
            )
        })
    }

    private fun modifyServerNickname() {
        nav(R.id.action_serverDetailsFragment_to_changingServerNameFragment, Bundle().apply {
            putParcelable(BUNDLE_DATA, mServerInfo)
        })
    }

    private fun createNewGroup() {
        nav(R.id.action_serverDetailsFragment_to_createGroupFragment, Bundle().apply {
            putParcelable(BUNDLE_DATA, mServerInfo)
        })
    }

    private fun createNewChannel() {
        mBaseApiViewModel.requestUniversally(
                viewModelScope = lifecycleScope,
                isShowToastTip = false,
                request = { appDataManage ->
                    appDataManage.requestServerGroup(mServerInfo.serverId)
                }
        ) { groups ->
            if (groups.isEmpty()) {
                toast("至少需要创建一个分组")
            } else {
                nav(R.id.action_serverDetailsFragment_to_channelCreateFragment, Bundle().apply {
                    putParcelable(
                            BUNDLE_DATA, BundleEntitySealed.BundleEntityFromRecommendSealed(
                            groups[0].groupId,
                            groups[0].groupName,
                            mServerInfo.serverId,
                            mServerInfo.fromType!!,
                            mServerInfo.serverName)
                    )
                })
            }
        }
    }

    private fun serverSettings() {
        nav(R.id.action_serverDetailsFragment_to_serverSettingsFragment, Bundle().apply {
            putParcelable(BUNDLE_DATA, mServerInfo)
        })
    }

    private fun invite() {
        nav(R.id.action_serverDetailsFragment_to_invitationRecordFragment, Bundle().apply {
            putString(BUNDLE_DATA, mServerInfo.serverId)
        })
    }

}



